import logging
import re

logger = logging.getLogger(__name__)


def remove_anchor_link(file_path: str):
    """
    去除锚点链接(Anchor Link),比如[跳转到章节1](#section1)
    """
    try:
        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
            md_content = f.read()
            md_content = re.sub(r"\[(.*?)\]\((.*?)\#.*?\)", r"[\1](\2)", md_content)
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(md_content)
    except Exception as e:
        logger.error(f"remove_anchor_link error: {e}", exc_info=True)


def replace_path_with_default_file(file_path: str, default_file: str):
    """
    替换路径为默认文件,[](../test/),替换为[](../test/index.md)
    """
    try:
        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
            md_content = f.read()
            link_pattern = r"\[([^\]]+)\]\(([^)]+)\)"
            matches = list(re.finditer(link_pattern, md_content))
            for match in matches:
                link_url = match.group(2)
                if link_url.endswith("/"):
                    md_content = md_content.replace(
                        f"({link_url})",
                        f"({link_url}{default_file})",
                    )
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(md_content)
    except Exception as e:
        logger.error(f"remove_anchor_link error: {e}", exc_info=True)
